<template>
    <h3>各种isRef，等等is方法主要是判断私有属性__v_isRef</h3>
    <h3>unref：val = isRef(val) ? val.value : val 计算的一个语法糖</h3>
    <h3>toRefs：遍历所有属性，逐个调用toRef组装成新的对象，数组同理</h3>
    <el-button @click="handleClick">click</el-button>
    <el-button @click="handleClick_toRefs">toRefs</el-button>
</template>

<script setup>
import {
    ref, isRef, reactive, isReactive,
    isProxy, readonly, isReadonly, unref,
    toRef, toRefs
} from "vue"

const foo_reactive = reactive({
    foo_reactive: 'foo_reactive'
})
const foo_ref = ref('foo_ref')
const foo_readonly = readonly({
    foo_readonly: 'foo_readonly'
})

let bar = 'bar'
let bar_proxy = {
    bar_proxy: 'bar_proxy',
    __v_raw: true
}

const handleClick = () => {
    console.log('foo_reactive:' + isReactive(foo_reactive));
    console.log('foo_ref:' + isRef(foo_ref));
    console.log('foo_readonly:' + isReadonly(foo_readonly));

    console.log('foo_reactive:' + foo_reactive.__v_isReactive);
    // console.log('foo_ref:' + foo_ref.__v_isRef);
    console.log('foo_readonly:' + foo_readonly.__v_isReadonly);

    console.log('foo_reactive_isProxy:' + isProxy(foo_reactive));
    // 新版vue3.4.25修改了判断逻辑，判断__v_raw属性
    console.log('bar_proxy_isProxy:' + isProxy(bar_proxy));

    console.log('bar:' + isRef(bar));
    console.log('bar:' + isReactive(bar));

    console.log(unref(foo_ref));
    console.log(unref(foo_reactive));

    // toRef
    const bar_to_ref = toRef(bar)
    const foo_reactive_to_ref = toRef(foo_reactive)
    const foo_ref_to_ref = toRef(foo_ref)
    console.log('bar_to_ref:', bar_to_ref); //普通字符串，返回ref
    console.log('foo_reactive_to_ref:', foo_reactive_to_ref.value); //返回ref，ref.value还是原reactive对象
    console.log('foo_ref_to_ref:', foo_ref_to_ref); //直接返回原始ref
}

// toRefs
const handleClick_toRefs = () => {
    // 对象形式
    const state = reactive({
        foo: 1,
        bar: 2
    })

    const { foo } = toRefs(state)
    // 这个 ref 和源属性已经“链接上了”
    state.foo++
    console.log(foo.value) // 2

    foo.value++
    console.log(state.foo) // 3

    // 数组形式
    const arr = reactive([1, 2, 3])
    const [a] = toRefs(arr)
    // 这个 ref 和源属性已经“链接上了”
    arr[0]++
    console.log(a.value) // 2

    a.value++
    console.log(arr[0]) // 3
}
</script>

<style lang="scss" scoped>
</style>